<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PageResult } from '#/api/common';
import type {
  OrderReturnDataType,
  SaleOrderForm,
  SaleOrderVO,
} from '#/api/hm/saleOrder/model';

import { computed, onMounted, reactive, ref } from 'vue';
// 1. 引入 useRouter 用于页面跳转
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { useUserStore } from '@vben/stores';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import { customerList } from '#/api/hm/customer';
import { productList } from '#/api/hm/product';
import {
  saleOrderExport,
  saleOrderInfo,
  saleOrderList,
  saleOrderRemove,
} from '#/api/hm/saleOrder';
import { deptList } from '#/api/system/dept';
import { commonDownloadExcel } from '#/utils/file/download';
import PaymentModal from '#/views/hm/saleOrder/component/PaymentModal.vue';
import PickupModal from '#/views/hm/saleOrder/component/PickupModal.vue';
// import saleOrderInfoDesc from '#/views/hm/saleOrder/component/sale-order-info-desc.vue'; // 3. 移除不再需要的详情弹窗组件
import saleOrderPickUpListModal from '#/views/hm/saleOrder/saleOrderPickUpList-modal.vue';
import saleOrderPickUpModal from '#/views/hm/saleOrderPickUp/saleOrderPickUp-modal.vue';

import SaleOrderReturnModal from './component/SaleOrderReturnModal.vue';
import { columns, querySchema } from './data';
import saleOrderModal from './saleOrder-modal.vue';

// 2. 初始化 router
const router = useRouter();
const useStore = useUserStore();

const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  return hasAccessByRoles(['admin', 'superadmin', 'ceo']);
});
const isStoreManage = computed(() => {
  return hasAccessByRoles(['shop-owner']);
});

// 财务
const isFinance = computed(() => {
  return hasAccessByRoles(['finance']);
});

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  fieldMappingTime: [
    [
      'saleOrderTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD', 'YYYY-MM-DD'],
    ],
    [
      'refundTimeRange',
      ['params[refundStartTime]', 'params[refundEndTime]'],
      ['YYYY-MM-DD', 'YYYY-MM-DD'],
    ],
  ],
};

const returnData = reactive({
  saleProductName: '合计',
  pickUpNum: 0,
  returnAmount: 0,
  refundSurplusNum: 0,
  surplusNum: 0,
  saleNum: 0,
  saleAmount: 0,
  refundAmount: 0,
});

const saleOrderId = ref('');

function calculateRowData(dataList: PageResult<SaleOrderVO>) {
  let totalPickUpNum = 0;
  let totalReturnAmount = 0;
  let totalRefundSurplusNum = 0;
  let totalSurplusNum = 0;
  let totalSaleNum = 0;
  let totalSaleAmount = 0;
  let totalRefundAmount = 0;

  dataList.rows.forEach((item) => {
    totalPickUpNum += Number(item.pickUpNum) || 0;
    totalReturnAmount += Math.round(Number(item.returnAmount) * 100) || 0;
    totalRefundSurplusNum += Number(item.refundSurplusNum) || 0;
    totalSurplusNum += Number(item.surplusNum) || 0;
    totalSaleNum += Number(item.saleNum) || 0;
    totalSaleAmount += Math.round(Number(item.saleAmount) * 100) || 0;
    totalRefundAmount += Math.round(Number(item.refundAmount) * 100) || 0;
  });

  returnData.pickUpNum = totalPickUpNum;
  returnData.returnAmount = totalReturnAmount / 1000;
  returnData.refundSurplusNum = totalRefundSurplusNum;
  returnData.surplusNum = totalSurplusNum;
  returnData.saleNum = totalSaleNum;
  returnData.saleAmount = totalSaleAmount / 100;
  returnData.refundAmount = totalRefundAmount / 100;
}

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
  },
  columns,
  height: 'auto',
  keepSource: true,
  showFooter: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const params = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        if (
          params.refundAmountRange &&
          Array.isArray(params.refundAmountRange)
        ) {
          params.minRefundAmount = params.refundAmountRange[0];
          params.maxRefundAmount = params.refundAmountRange[1];
          delete params.refundAmountRange;
        }

        if (params.surplusNumRange && Array.isArray(params.surplusNumRange)) {
          params.minSurplusNum = params.surplusNumRange[0];
          params.maxSurplusNum = params.surplusNumRange[1];
          delete params.surplusNumRange;
        }
        const data = await saleOrderList(params);
        calculateRowData(data);
        return data;
      },
    },
  },
  footerData: [returnData],
  rowConfig: {
    keyField: 'saleId',
    height: 60,
  },
  id: 'hm-saleOrder-index',
};

const checked = ref(false);
const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [SaleOrderModal, modalApi] = useVbenModal({
  connectedComponent: saleOrderModal,
});

const [SaleOrderPickUpModal, pickUpModalApi] = useVbenModal({
  connectedComponent: saleOrderPickUpModal,
});

const [SaleOrderPickUpListModal, pickUpModalListApi] = useVbenModal({
  connectedComponent: saleOrderPickUpListModal,
});

// 3. 移除不再需要的详情弹窗 Modal
// const [SaleOrderInfoModal, infoApi] = useVbenModal({
//   connectedComponent: saleOrderInfoDesc,
// });

function handleAdd() {
  modalApi.setData({});
  modalApi.open();
}

async function handleEdit(row: Required<SaleOrderForm>) {
  modalApi.setData({ id: row.saleId });
  modalApi.open();
}

/**
 * 4. 修改 handleInfo 函数，实现页面跳转
 * @param row 当前行数据
 */
async function handleInfo(row: Required<SaleOrderForm>) {
  // 使用 router.push 跳转到新的详情页
  router.push({ name: 'SaleOrderDetail', params: { id: row.saleId } });
}

// 打开业务处理模块
async function handleBusiness(row: Required<SaleOrderForm>) {
  pickUpModalApi.setData({ saleOrderId: row.saleId, isGift: row.isGift });
  pickUpModalApi.open();
}

// 打开回款、提货历史模块
async function handlePickUpHis(row: Required<SaleOrderForm>, type: String) {
  pickUpModalListApi.setData({
    saleOrderId: row.saleId,
    pickUpType: type,
    productId: row.saleProductId,
  });
  pickUpModalListApi.open();
}

async function handleDelete(row: Required<SaleOrderForm>) {
  await saleOrderRemove(row.saleId);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<SaleOrderForm>) => row.saleId);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await saleOrderRemove(ids);
      await tableApi.query();
      checked.value = false;
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(
    saleOrderExport,
    '销售订单数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

onMounted(async () => {
  const requestParams = { ancestors: '101', deptCategory: 'DP' };
  const deptTree = await deptList(requestParams);
  const deptOptions = [];
  const deptTransOptions = deptTree.map((item) => ({
    label: item.deptName,
    value: item.deptId,
  }));
  deptOptions.push(...deptTransOptions);
  tableApi.formApi.updateSchema([
    {
      fieldName: 'saleDept',
      componentProps: {
        options: deptOptions,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
    {
      fieldName: 'recordEndLocation',
      componentProps: {
        options: deptOptions,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
  ]);
});

onMounted(async () => {
  const ret = await productList({
    pageNum: 1,
    pageSize: 999,
    status: '0',
    productType: 'CP',
  });
  const dataSourceOptions = [];
  const transOptions = ret.rows.map((item) => ({
    label: item.productName,
    value: item.productId.toString(),
  }));
  dataSourceOptions.push(...transOptions);
  tableApi.formApi.updateSchema([
    {
      fieldName: 'saleProductId',
      componentProps: {
        options: dataSourceOptions,
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
  ]);
});
const nowDept = ref<number | string>();

onMounted(async () => {
  nowDept.value = useStore.userInfo?.deptId;
  const ret = await customerList({
    pageNum: 1,
    pageSize: 999,
    ...(!(isAdmin.value || isStoreManage.value || isFinance.value) && {
      storeId: nowDept.value,
    }),
  });
  const dataSourceOptions = [];
  const transOptions = ret.rows.map((item) => ({
    label: item.customerName,
    value: item.customerId.toString(),
  }));
  dataSourceOptions.push(...transOptions);
  tableApi.formApi.updateSchema([
    {
      fieldName: 'customer',
      componentProps: {
        options: dataSourceOptions,
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
      },
    },
  ]);
});

const showReturnModal = ref(false);
const currentOrderForReturn = ref<null | OrderReturnDataType>(null);
const paymentModalVisible = ref(false);
const pickupModalVisible = ref(false);

const handleOpenReturnModal = (orderRecord: any) => {
  const unitPrice =
    orderRecord.saleNum > 0 ? orderRecord.saleAmount / orderRecord.saleNum : 0;

  const transformedOrderData: OrderReturnDataType = {
    saleId: orderRecord.saleId,
    paidAmount: orderRecord.returnAmount,
    productA: {
      productId: orderRecord.saleProductId || 'UNKNOWN_PROD_ID',
      productName: orderRecord.saleProductName || '主产品',
      totalSold: orderRecord.saleNum || 0,
      pickedQty: orderRecord.pickUpNum || 0,
      unpickedQty: orderRecord.surplusNum || 0,
      unitPrice,
      alreadyReturnedPickedQty:
        orderRecord.mainProductPreviouslyReturnedPickedQty || 0,
      alreadyReturnedUnpickedQty:
        orderRecord.mainProductPreviouslyReturnedUnpickedQty || 0,
    },
    gifts:
      orderRecord.giftList?.map((gift: any) => {
        return {
          giftId: gift.giftProductId || 'UNKNOWN_GIFT_ID',
          giftName: gift.giftProductName || '赠品',
          totalGiven: gift.giftNum || 0,
          pickedQty: gift.giftUsedNum || 0,
          unpickedQty: (gift.giftNum || 0) - (gift.giftUsedNum || 0),
          alreadyReturnedPickedQty: gift.pickedQty || 0,
          alreadyReturnedUnpickedQty: gift.unpickedQty || 0,
        };
      }, []) || [],
  };
  currentOrderForReturn.value = transformedOrderData;
  showReturnModal.value = true;
};

const handleReturnSuccess = () => {
  console.log('退货申请成功，需要刷新列表');
};
const currentOrder = ref<null | SaleOrderVO>(null); // 用于存储当前操作的订单数据
// 4. 新增：打开收款弹窗的处理函数
async function handleOpenPaymentModal(record: SaleOrderVO) {
  // 为了确保数据最准确实时，先从接口获取完整的订单详情
  const fullOrderData = await saleOrderInfo(record.saleId);
  saleOrderId.value = record.saleId;
  currentOrder.value = fullOrderData;
  paymentModalVisible.value = true;
}

// 5. 新增：打开提货弹窗的处理函数
async function handleOpenPickupModal(record: SaleOrderVO) {
  const fullOrderData = await saleOrderInfo(record.saleId);
  saleOrderId.value = record.saleId;
  currentOrder.value = fullOrderData;
  pickupModalVisible.value = true;
}

function handleSuccess() {
  tableApi.query();
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="销售订单列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['hm:saleOrder:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['hm:saleOrder:remove']"
            @click="handleMultiDelete"
            v-if="isAdmin"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['hm:saleOrder:add']"
            @click="handleAdd"
          >
            {{ $t('产品销售') }}
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button @click="handleOpenPaymentModal(row)">收款</ghost-button>
          <ghost-button type="primary" @click="handleOpenPickupModal(row)">
            提货
          </ghost-button>
          <ghost-button
            danger
            @click.stop="handleOpenReturnModal(row)"
            v-access:code="['hm:saleOrder:edit']"
            v-if="isAdmin || row.saleUser === useStore.userInfo?.userId"
          >
            退货
          </ghost-button>
          <ghost-button
            v-if="isAdmin"
            v-access:code="['hm:saleOrder:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <ghost-button @click.stop="handleInfo(row)"> 详情 </ghost-button>
          <Popconfirm
            v-if="isAdmin"
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['hm:saleOrder:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
      <template #refundAmountHis="{ row }">
        <a-button
          style="color: green"
          type="text"
          @click="handlePickUpHis(row, 'refundAmountHis')"
        >
          {{ row.returnAmount / 10 }}
        </a-button>
      </template>
      <template #pickUpNumHis="{ row }">
        <a-button
          style="color: green"
          type="text"
          @click="handlePickUpHis(row, 'pickUpNumHis')"
        >
          {{ row.pickUpNum }}
        </a-button>
      </template>
    </BasicTable>
    <SaleOrderModal @reload="tableApi.query()" />
    <!-- 业务处理模块 -->
    <SaleOrderPickUpModal @reload="tableApi.query()" />
    <!-- 提货、回款历史模块 -->
    <SaleOrderPickUpListModal @reload="tableApi.query()" />
    <!-- 3. 移除不再需要的详情弹窗 Modal -->
    <!-- <SaleOrderInfoModal @reload="tableApi.query()" /> -->

    <SaleOrderReturnModal
      v-model:visible="showReturnModal"
      :order-data-input="currentOrderForReturn"
      @success="handleReturnSuccess"
    />
    <PaymentModal
      v-model:visible="paymentModalVisible"
      :order-id="saleOrderId"
      :order-data="currentOrder"
      @success="handleSuccess"
    />
    <PickupModal
      v-model:visible="pickupModalVisible"
      :order-id="saleOrderId"
      :order-data="currentOrder"
      @success="handleSuccess"
    />
  </Page>
</template>
